<template>
  <div class="track-player-container">
    <div id="container" class="map-container"></div>
    <div class="input-card">
      <h4>轨迹回放控制</h4>
      <div class="btn-group">
        <button class="btn" :disabled="isPlaying" @click="startAnimation">开始动画</button>
        <button class="btn" :disabled="!isPlaying" @click="pauseAnimation">暂停动画</button>
      </div>
      <div class="btn-group">
        <button class="btn" :disabled="!isPaused" @click="resumeAnimation">继续动画</button>
        <button class="btn" :disabled="!isPlaying && !isPaused" @click="stopAnimation">停止动画</button>
      </div>
      <div id="progress-container">
        <div id="progress-bar" :style="{ width: progress + '%' }"></div>
      </div>
      <div id="status">{{ statusText }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 轨迹数据
const trackPoints = [
  [116.478935,39.997761],[116.478939,39.997825],[116.478912,39.998549],
  [116.478912,39.998549],[116.478998,39.998555],[116.478998,39.998555],
  [116.479282,39.99856],[116.479658,39.998528],[116.480151,39.998453],
  [116.480784,39.998302],[116.480784,39.998302],[116.481149,39.998184],
  [116.481573,39.997997],[116.481863,39.997846],[116.482072,39.997718],
  [116.482362,39.997718],[116.483633,39.998935],[116.48367,39.998968],
  [116.484648,39.999861]
]

// 状态管理
const isPlaying = ref(false)
const isPaused = ref(false)
const progress = ref(0)
const statusText = ref('准备就绪')

let map = null
let marker = null
let polyline = null
let passedPolyline = null

// 初始化地图
const initMap = () => {
  return new Promise((resolve, reject) => {
    // 检查高德地图API是否已加载
    if (!window.AMap) {
      const script = document.createElement('script')
      script.src = 'https://webapi.amap.com/maps?v=2.0&key=a2ece4b6cda867ff3ac394a4a44f2f4f'
      script.onload = () => resolve()
      script.onerror = () => reject(new Error('高德地图API加载失败'))
      document.head.appendChild(script)
    } else {
      resolve()
    }
  }).then(() => {
    // 加载动画插件
    return new Promise((resolve, reject) => {
      AMap.plugin('AMap.MoveAnimation', () => resolve())
    })
  }).then(() => {
    // 创建地图实例
    map = new AMap.Map('container', {
      resizeEnable: true,
      center: [116.397428, 39.90923],
      zoom: 17
    })

    // 创建轨迹线
    polyline = new AMap.Polyline({
      map: map,
      path: trackPoints,
      showDir: true,
      strokeColor: "#28F",
      strokeWeight: 6
    })

    // 创建已走过的轨迹线
    passedPolyline = new AMap.Polyline({
      map: map,
      strokeColor: "#AF5",
      strokeWeight: 6
    })

    // 创建移动标记
    marker = new AMap.Marker({
      map: map,
      position: trackPoints[0],
      icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png", // "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png"
      offset: new AMap.Pixel(-13, -26)
    })

    // 监听移动事件，更新已走过的轨迹
    marker.on('moving', function(e) {
      passedPolyline.setPath(e.passedPath)
      map.setCenter(e.target.getPosition(), true)

      // 更新进度
      const progressValue = (e.passedPath.length / trackPoints.length) * 100
      progress.value = Math.min(100, Math.max(0, progressValue))
      statusText.value = `正在播放: ${progress.value.toFixed(1)}%`
    })

    // 监听移动结束事件
    marker.on('moveend', function() {
      isPlaying.value = false
      isPaused.value = false
      statusText.value = '播放结束'
    })

    map.setFitView()
    statusText.value = '地图初始化完成'
  }).catch(error => {
    console.error('地图初始化失败:', error)
    statusText.value = '地图加载失败，请检查API Key'
  })
}

// 开始动画
const startAnimation = () => {
  if (!marker || isPlaying.value) return

  statusText.value = '开始播放轨迹...'
  isPlaying.value = true
  isPaused.value = false

  marker.moveAlong(trackPoints, {
    duration: 500,
    autoRotation: true
  })
}

// 暂停动画
const pauseAnimation = () => {
  if (!marker || !isPlaying.value || isPaused.value) return

  marker.pauseMove()
  isPaused.value = true
  statusText.value = '已暂停'
}

// 恢复动画
const resumeAnimation = () => {
  if (!marker || !isPaused.value) return

  marker.resumeMove()
  isPaused.value = false
  statusText.value = '继续播放'
}

// 停止动画
const stopAnimation = () => {
  if (!marker || (!isPlaying.value && !isPaused.value)) return

  marker.stopMove()
  isPlaying.value = false
  isPaused.value = false
  progress.value = 0
  passedPolyline.setPath([])
  statusText.value = '已停止'
}

// 组件挂载后初始化地图
onMounted(() => {
  statusText.value = '地图加载中...'
  initMap()
})

// 组件卸载前清理资源
onUnmounted(() => {
  if (marker) {
    marker.off('moving')
    marker.off('moveend')
    marker.setMap(null)
    marker = null
  }

  if (polyline) {
    polyline.setMap(null)
    polyline = null
  }

  if (passedPolyline) {
    passedPolyline.setMap(null)
    passedPolyline = null
  }

  if (map) {
    map.destroy()
    map = null
  }
})
</script>

<style scoped>
.map-container {
  height: 100vh;
  width: 100%;
}

.input-card {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 100;
  background-color: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  max-width: 300px;
}

.input-card h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
}

.btn-group {
  display: flex;
  margin-bottom: 15px;
}

.btn {
  flex: 1;
  margin-right: 10px;
  padding: 8px 12px;
  background-color: #4080ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn:last-child {
  margin-right: 0;
}

.btn:hover {
  background-color: #3070e0;
}

.btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

#progress-container {
  margin-top: 15px;
  height: 10px;
  background-color: #f3f3f3;
  border-radius: 5px;
  overflow: hidden;
}

#progress-bar {
  height: 100%;
  background-color: #4080ff;
  width: 0%;
  transition: width 0.3s;
}

#status {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}
</style>
